//
//  JJWebViewController.m
//  DemoPro
//
//  Created by vpjacob on 2017/5/28.
//  Copyright © 2017年 vpjacob. All rights reserved.
//

#import "JJWebViewController.h"
#import <JavaScriptCore/JavaScriptCore.h>
#import "JJOCJSModel.h"
#import <MJRefresh.h>


NSString *const JJWebJavaScriptContext = @"documentView.webView.mainFrame.javaScriptContext";
NSString *const JJWebDocumentTitles = @"document.title";

@interface JJWebViewController ()
@property (nonatomic, copy) NSString *requestUrlStr;

@end

@implementation JJWebViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self.view addSubview:self.webView];
}

- (void)loadWebView{
    NSString *urlStr = self.urlString;
    if (![urlStr hasPrefix:@"http"]) {
        urlStr = [NSString stringWithFormat:@"http://%@", self.urlString];
    }
//    NSURLRequest *req = [NSURLRequest requestWithURL:[NSURL URLWithString:urlStr]];
//    [self.webView loadRequest:req];
    
    NSURL *url = [[NSBundle mainBundle] URLForResource:@"demo" withExtension:@"html"];
    [self.webView loadRequest:[NSURLRequest requestWithURL:url]];
    
}

#pragma mark -  UIWebViewDelegate
- (void)webViewDidStartLoad:(UIWebView *)webView {
    [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:YES];
}

- (void)webViewDidFinishLoad:(UIWebView *)webView {
    JSContext *context = [self.webView valueForKeyPath:@"documentView.webView.mainFrame.javaScriptContext"];
    
    JJOCJSModel *objectModel = [JJOCJSModel new];
    
    context[@"native"] =  objectModel;

    objectModel.myBlock = ^(NSString *name) {
        NSLog(@"%@",name);
    };

}



- (UIWebView *)webView {
    if (!_webView) {
        _webView = [[UIWebView alloc] initWithFrame:CGRectMake(0, 0, JJ_SCREEN_WIDTH, JJ_SCREEN_HEIGHT - 64)];
        _webView.backgroundColor = [UIColor whiteColor];
        _webView.delegate = self;
        _webView.opaque = NO;
    }
    return _webView;
}

- (void)setUrlString:(NSString *)aUrlString {
    if (_urlString != aUrlString) {
        _urlString = aUrlString;
        //        self.requestUrlStr = [KNBBaseRequest appendSecretUrlStr:aUrlString];
        self.requestUrlStr = aUrlString;
        if (![self.requestUrlStr hasPrefix:@"http"]) {
            self.requestUrlStr = [NSString stringWithFormat:@"http://%@",self.requestUrlStr];
        }
        [self loadWebView];
    }
}

@end
